package chujisuanfa;

public class Atoi {
    public static int myAtoi(String s) {
        if(s.length()==0) return 0;
        int i=0;
        while(i<s.length()&&s.charAt(i)==' ') i++;//去前导空格
        boolean flag=true; //表示正数
        // max=2147483647
        // min=-2147483648
        if(i<s.length()&&s.charAt(i)=='-'){ //判断正负
            i++;
            flag=false;
        }else if(i<s.length()&&s.charAt(i)=='+'){
            i++;
        }
        int c;
        int target=0;
        if(i<s.length()&&Character.isDigit(s.charAt(i))){
            target = s.charAt(i)-'0';
            i++;
        }else{
            return 0;
        }
        while(i<s.length()&&Character.isDigit(s.charAt(i))){
            c = s.charAt(i)-'0';
            if(target>Integer.MAX_VALUE/10){
                return flag?Integer.MAX_VALUE:Integer.MIN_VALUE;
            }else if(target==Integer.MAX_VALUE/10){
                if((flag&&c<=7)||(!flag&&c<=8)){
                    target*=10;
                    target+=c;
                    i++;
                    continue;
                }else{
                    return flag?Integer.MAX_VALUE:Integer.MIN_VALUE;
                }
            }
            target*=10;
            target+=c;
            i++;
        }
        return flag?target:-target;
    }

    public static void main(String[] args) {
//        System.out.println(myAtoi("  -+"));
        StringBuilder sb = new StringBuilder();
        String a = new String("a");
        String b = new String("a");
        System.out.println(a.equals(b));
        System.out.println(a==b);
        sb.append("ss");
        sb.toString();
    }
}
